<template>
  <div class="container">
    <!-- 左侧笔记列表 -->
    <div class="sidebar">
      <div class="search-bar" style="margin-bottom: 20px">
        <el-row>
          <el-col :span="18">
            <el-input
              placeholder="搜索笔记"
              clearable
              v-model="queryParams.articleTitle"
              @clear="queryParams.articleTitle = ''"
            />
          </el-col>
          <el-col :span="5" :offset="1">
            <el-button @click="openAddDialog" type="success">+</el-button>
          </el-col>
        </el-row>
      </div>
      <el-collapse v-model="activeNames" accordion>
        <div v-for="(group, index) in groupedNotes" :key="index" class="note-group">
          <el-collapse-item :name="index.toString()">
            <template #title>
              <span>{{ group.noteType }}</span>
            </template>
            <div v-if="group.notes && group.notes.length === 0">没有笔记</div>
            <div v-for="note in group.notes" :key="note.id" class="note-item" :class="{ 'active': currentArticle?.id === note.id }" @click="selectNote(note)">
              <div class="note-content">
                <el-icon class="note-icon"><Document /></el-icon>
                <span class="title">{{ note.articleTitle }}</span>
              </div>
              <el-button class="edit-btn" type="primary" :icon="Edit" circle @click.stop="handleEdit(note)" />
              <el-button class="deleted-btn" type="danger" :icon="Delete" circle @click.stop="handleDelete(note)" />
            </div>
          </el-collapse-item>
        </div>
      </el-collapse>
    </div>

    <!-- 右侧内容区域 -->
    <div class="content">
      <div v-if="currentArticle" class="toolbar">
        <div v-if="isEditMode" style="display: inline-block;margin-right: 20px">
          <h3 v-if="!showTitle && currentArticle.articleTitle!==''" @dblclick="editTitle">{{currentArticle.articleTitle}}</h3>
          <el-input v-else ref="articleTitleInput" v-model="currentArticle.articleTitle" style="width: 400px;margin-right: 50px" @blur="showTitle=false"></el-input>
        </div>

        <el-button v-if="isEditMode" type="success" @click="handleSave" style="right: 50px;position: absolute">
          保存修改
        </el-button>
      </div>

      <bytemd-editor
        v-if="isEditMode"
        :locale="zhHans"
        :value="currentArticle.articleContent"
        :plugins="plugins"
        mode="auto"
        @change="handleEditorChange"
      />
      <bytemd-viewer
        v-else
        :locale="zhHans"
        :value="currentArticle.articleContent"
        :plugins="plugins"
        @updated="handleViewerUpdated"
      />
    </div>

    <!-- 新增笔记弹框 -->
    <el-dialog title="新增笔记" v-model="addDialogVisible">
      <el-form :model="newNote">
        <el-form-item label="笔记名称" required>
          <el-input v-model="newNote.articleTitle" placeholder="请输入笔记名称"></el-input>
        </el-form-item>
        <el-form-item label="笔记类型" required>
          <el-input v-model="newNote.noteType" placeholder="请输入笔记类型"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddNote">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick, watch, computed} from 'vue'
import {ElMessage} from 'element-plus'
import {Delete, Document, Edit} from '@element-plus/icons-vue'
import {listNote, addNote, updateNote, delNote} from "@/api/weblog/note"
import {Editor as BytemdEditor, Viewer as BytemdViewer} from '@bytemd/vue-next'
import highlight from '@bytemd/plugin-highlight'
import gfm from "@bytemd/plugin-gfm"
import zhHans from "bytemd/lib/locales/zh_Hans.json";
import footnotes from "@bytemd/plugin-footnotes"
import frontmatter from "@bytemd/plugin-frontmatter"
import { groupBy } from 'lodash'; // 确保安装 lodash

import 'bytemd/dist/index.css';
// import "github-markdown-css/github-markdown-dark.css";
// import "highlight.js/styles/default.css";
// import "github-markdown-css/github-markdown-light.css";
import 'juejin-markdown-themes/dist/juejin.min.css';
import '@/assets/css/markdown-highlight-bytemd.css'
import '@/assets/css/code-theme-light.css'
import '@/assets/css/code-theme-dark.css'
// 文章数据
const articleList = ref([])
const articleTitleInput = ref(null)
const { proxy } = getCurrentInstance();
const loading = ref(true);
const currentArticle = ref({articleContent: '', articleTitle: ''})
const isEditMode = ref(false)
const queryParams = ref({
  page: 1,
  pageSize: 10,
  articleTitle: ''
})

const showTitle = ref(false);

// ByteMD插件配置
const plugins = [
  highlight(),
  gfm(),
  footnotes(),
  frontmatter(),
]

// 在 setup 中添加主题状态
const isDarkTheme = ref(false)

const activeNames = ref(['0']); // 默认打开第一个分类

const editTitle = () => {
  showTitle.value = true;
  nextTick(() => {
    if (articleTitleInput.value) {
      articleTitleInput.value.focus();
    }
  });
};
const handleAdd = () => {
  isEditMode.value = true
  currentArticle.value = {
    articleContent: '',
    articleTitle: ''
  }
}
// 获取文章列表
const getList = () => {
  listNote().then(response => {
    articleList.value = response.rows; // 确保这里的 response.rows 包含 noteType 字段
    console.log(response.rows);
    if (articleList.value.length > 0) {
      currentArticle.value = articleList.value[0];
    }
  }).catch(error => {
    ElMessage.error('获取笔记列表失败');
  });
}

// 选择文章
const selectNote = (note) => {
  if (isEditMode.value) {
    ElMessage.warning('请先保存当前修改')
    return
  }
  currentArticle.value = note
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除笔记名称为"' + row.articleTitle + '"的数据项？').then(function() {
    loading.value = true;
    return delNote(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

// 编辑文章
const handleEdit = (note) => {
  currentArticle.value = note
  isEditMode.value = true
}

// 保存文章
const handleSave = async () => {

  if (!currentArticle.value.id) {
    await addNote(currentArticle.value)
  }else {
    await updateNote(currentArticle.value)
  }
  ElMessage.success('保存成功')
  getList();
  isEditMode.value = false
  await nextTick()  // 等待 DOM 更新
  addCopyButtons()  // 手动触发按钮添加
}

// 编辑器内容变化处理
const handleEditorChange = (value) => {
  currentArticle.value.articleContent = value
}

const handleViewerUpdated = () => {
  nextTick(addCopyButtons)
}

// 修改 addCopyButtons 函数
const addCopyButtons = () => {
  nextTick(()=>{
    const codeBlocks = document.querySelectorAll('.content .markdown-body pre code')
    codeBlocks.forEach(codeBlock => {
      const pre = codeBlock.parentElement
      if (pre.querySelector('.code-toolbar')) return

      // 创建 toolbar
      const toolbar = document.createElement('div')
      toolbar.className = 'code-toolbar'

      // 获取代码类型
      const className = codeBlock.className
      const language = className.replace('language-', '')

      // 创建语言标签
      const languageLabel = document.createElement('span')
      languageLabel.className = 'code-language'
      languageLabel.textContent = '代码类型:' + language || 'text'

      // 创建主题切换按钮
      const themeToggle = document.createElement('button')
      themeToggle.className = 'theme-toggle'
      themeToggle.innerHTML = `
        <svg viewBox="0 0 24 24" width="14" height="14">
          <path fill="currentColor" d="M12,18C11.11,18 10.26,17.8 9.5,17.45C11.56,16.5 13,14.42 13,12C13,9.58 11.56,7.5 9.5,6.55C10.26,6.2 11.11,6 12,6A6,6 0 0,1 18,12A6,6 0 0,1 12,18M20,8.69V4H15.31L12,0.69L8.69,4H4V8.69L0.69,12L4,15.31V20H8.69L12,23.31L15.31,20H20V15.31L23.31,12L20,8.69Z"/>
        </svg>
      `

      // 创建复制按钮
      const button = document.createElement('button')
      button.className = 'copy-btn'
      button.innerHTML = `
        <svg viewBox="0 0 24 24" width="14" height="14">
          <path fill="currentColor" d="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z"/>
        </svg>
      `

      button.onclick = async () => {
        try {
          const codeText = codeBlock.innerText || codeBlock.textContent;
          if (!codeText) {
            ElMessage.error('没有找到可复制的内容');
            return;
          }

          // 创建临时输入框
          const tempInput = document.createElement('textarea');
          tempInput.value = codeText.trim();
          document.body.appendChild(tempInput);
          tempInput.select();
          document.execCommand('copy'); // 执行复制
          document.body.removeChild(tempInput); // 移除临时输入框

          button.innerHTML = `
            <svg viewBox="0 0 24 24" width="14" height="14">
              <path fill="currentColor" d="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41-1.41L9,16.17z"/>
            </svg>
          `;
          ElMessage.success('复制成功');
          setTimeout(() => {
            button.innerHTML = `
              <svg viewBox="0 0 24 24" width="14" height="14">
                <path fill="currentColor" d="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z"/>
              </svg>
            `;
          }, 2000);
        } catch (err) {
          console.error('复制失败:', err);
          ElMessage.error('复制失败，请检查浏览器权限设置');
        }
      }

      // 主题切换逻辑
      themeToggle.onclick = () => {
        pre.classList.toggle('dark-theme')
      }

      // 将按钮添加到 toolbar
      const buttonGroup = document.createElement('div')
      buttonGroup.className = 'button-group'
      buttonGroup.appendChild(themeToggle)
      buttonGroup.appendChild(button)

      toolbar.appendChild(languageLabel)
      toolbar.appendChild(buttonGroup)

      pre.insertBefore(toolbar, pre.firstChild)
    })
  })
}

// 添加监听确保内容更新时重新添加按钮
watch(() => currentArticle.value?.articleContent, addCopyButtons)
watch(isEditMode, addCopyButtons)

// 监听编辑模式变化
watch(isEditMode, (newVal) => {
  if (!newVal) {
    nextTick(() => {
      const container = document.querySelector('.preview-content')
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    })
  }
})

// 文章数据
const groupedNotes = computed(() => {
  const grouped = groupBy(articleList.value, 'noteType'); // 确保这里的 articleList.value 包含 noteType 字段
  return Object.keys(grouped).map(key => ({
    noteType: key,
    notes: grouped[key]
  })); // 确保返回的对象包含 noteType 和 notes
});

const addDialogVisible = ref(false); // 控制弹框显示
const newNote = ref({ articleTitle: '', noteType: '' }); // 新增笔记的数据

const openAddDialog = () => {
  console.log('打开新增笔记弹框')
  newNote.value = { articleTitle: '', noteType: '' }; // 重置数据
  addDialogVisible.value = true; // 打开弹框
};

const handleAddNote = () => {
  console.log('新增笔记数据:', newNote.value); // 添加调试信息
  if (!newNote.value.articleTitle || !newNote.value.noteType) {
    ElMessage.warning('请填写笔记名称和类型');
    return;
  }

  // 调用新增笔记的 API
  addNote({
    articleTitle: newNote.value.articleTitle,
    noteType: newNote.value.noteType,
    articleContent: '' // 可以根据需要设置初始内容
  }).then(() => {
    ElMessage.success('新增笔记成功');
    getList(); // 刷新笔记列表
    addDialogVisible.value = false; // 关闭弹框
  }).catch((error) => {
    console.error('新增笔记失败:', error); // 捕获并打印错误
    ElMessage.error('新增笔记失败');
  });
};

onMounted(() => {
  getList()
  nextTick(()=>{
    addCopyButtons()
  })

})
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
  background: #f8fafc;
}

.sidebar {
  width: 280px;
  padding: 16px;
  background: white;
  border-right: 1px solid #e2e8f0;
  overflow-y: auto;
}

.note-item {
  position: relative;
  padding: 12px 16px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.note-item:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.08);
}

.note-item.active {
  background: #f0f9ff;
  border-left: 3px solid #38bdf8;
}

.note-content {
  flex: 1;
  display: flex;
  align-items: center;
  overflow: hidden;
}

.note-icon {
  margin-right: 12px;
  color: #94a3b8;
  font-size: 18px;
}

.title {
  font-size: 14px;
  color: #334155;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.edit-btn {
  position: absolute;
  right: 12px;
  opacity: 0;
  transition: opacity 0.2s;
  padding: 6px;
}

.edit-btn :deep(svg) {
  width: 16px;
  height: 16px;
}

.deleted-btn {
  position: absolute;
  right: 48px;
  opacity: 0;
  transition: opacity 0.2s;
  padding: 6px;
  z-index: 100;
}

.deleted-btn :deep(svg) {
  width: 16px;
  height: 16px;
}


.note-item:hover .edit-btn {
  opacity: 1;
}

.note-item:hover .deleted-btn {
  opacity: 1;
}

.content {
  flex: 1;
  padding: 24px;
  background: white;
  overflow-y: auto;
}

.toolbar {
  margin-bottom: 20px;
}

.preview-content {
  height: calc(100vh - 100px);
  overflow-y: auto;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

/* ByteMD编辑器样式 */
:deep(.bytemd) {
  height: calc(100vh - 100px);
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

/* 修改代码块样式 */
:deep(.preview-content) pre {
  position: relative;
  margin: 12px 0;
  border-radius: 6px;
  padding: 0 0 1em 0;
}

/* 按钮组样式 */
:deep(.button-group) {
  display: flex;
  gap: 8px;
}

/* 主题切换按钮样式 */
:deep(.theme-toggle) {
  padding: 4px 8px;
  background: transparent;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.theme-toggle:hover) {
  background: #409EFF;
  border-color: #409EFF;
}

:deep(.theme-toggle:hover svg) {
  color: white;
}

/* toolbar 基础样式 */
:deep(.code-toolbar) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
}

:deep(.code-language) {
  font-size: 12px;
  font-family: Monaco, monospace;
  text-transform: lowercase;
}

:deep(.copy-btn) {
  padding: 4px 8px;
  background: transparent;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}
:deep(.markdown-body p) {
  white-space: pre-wrap;
}
:deep(.markdown-body){
  font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;
}


</style>
